package com.macoli.mock_server.common

import com.macoli.mock_server.MockService
import com.macoli.mock_server.httpserver.beans.HTTP_METHOD
import com.macoli.mock_server.di.component.DaggerBaseComponent
import com.macoli.mock_server.httpserver.route.Router
import com.macoli.mock_server.utils.FileUtils
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.FileInputStream
import javax.inject.Inject


class Configuration @Inject constructor() {
    var port : Int = 8080
    lateinit var hostName : String
    lateinit var basePath : String
    @Inject
    lateinit var router : Router

    init {
        MockService.getMockService().getBaseComponent().injectConfiguration(this)
    }

    suspend fun parseConfiguration(configPath: String) {
        val fileData = FileUtils.readFile(configPath + "mock_server_config.json")
        val rootObj = JSONObject(fileData)
        port = rootObj.optInt("port")
        hostName = rootObj.optString("hostName")
        basePath = rootObj.optString("base_path")
        val routingTableObj = rootObj.optJSONObject("routing_table")
        val getArray = routingTableObj?.optJSONArray("get")

        if (getArray != null) {
            val size = getArray.length()
            for (i in 0 until size) {
                val routeItemObj : JSONObject = getArray[i] as JSONObject
                router.addRouteItem(HTTP_METHOD.GET , routeItemObj.optString("uri") ,
                                    routeItemObj.optString("default_path") ,
                                    routeItemObj.optBoolean("static" , false))
            }
        }

        val postArray = routingTableObj?.optJSONArray("post")
        if (postArray != null) {
            val size = postArray.length()
            for (i in 0 until size) {
                val routeItemObj : JSONObject = postArray[i] as JSONObject
                router.addRouteItem(HTTP_METHOD.GET , routeItemObj.optString("uri") ,
                    routeItemObj.optString("default_path") ,
                    routeItemObj.optBoolean("static" , false))
            }
        }
    }
}